package zheezes.protocol.impl.gbw;

import org.apache.log4j.Logger;

import zheezes.protocol.Frame;
import zheezes.protocol.PacketAnalyzer;
import zheezes.util.ArrayUtil;
import zheezes.util.ByteUtil;


public class GbwPacketAnalyzer extends PacketAnalyzer{
	private static Logger logger = Logger.getLogger(GbwPacketAnalyzer.class);
	
	static {
		logger.debug("loaded");
	}
	
	@Override
	public int[] checkPacket(byte[] buf, int length) {
		int idx = 0;
		int len = length;
		int dataLen;// L
		byte chksum = 0x00;// cs

		while ((idx = ArrayUtil.find(buf, idx, len, (byte) 0x68)) >= 0) {
			len = len - idx;
			if (len >= 6 + 6 + 2) {
				if (buf[idx + 5] == 0x68) {
					if (buf[idx + 1] == buf[idx + 3] && buf[idx + 2] == buf[idx + 4]) {
						dataLen = ByteUtil.ctos(buf, idx + 1) >>> 2;
						chksum = (byte) ArrayUtil.sum(buf, idx + 6, dataLen);
						if ((buf[idx + dataLen + 6] == chksum) && (buf[idx + dataLen + 7] == 0x16)) {
							return new int[] { idx, dataLen + 8 };
						}
					}
				}
			} else {// not enough length
				return new int[]{idx, -1};
			}
			idx++;
		}
		// don't have a valid frame header
		return new int[]{length, -1};
	}

	@Override
	public Frame parse(byte[] buf, int length) {
		GbwFrame frame = new GbwFrame(buf, 0);
		if(frame.size() != length) {
			return null;
		}
		return frame;
	}
}
